package logic

import (
	"context"
	"fmt"
	"math/rand"
	"strconv"
	"time"
	"zk/product_zy17/models/cache"
	"zk/product_zy17/pkg"

	"zk/product_zy17/productRpc/internal/svc"
	"zk/product_zy17/productRpc/productRpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendSmsLogic) SendSms(in *productRpc.SendSmsRequest) (*productRpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	code := rand.Intn(9000) + 1000

	sms, err := pkg.SensSms(in.Tel, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}

	if *sms.Body.Code != "OK" {
		return nil, fmt.Errorf(*sms.Body.Code)
	}

	cache.RedisDB.Set(l.ctx, "sendSms"+in.Tel, code, time.Minute*5)

	return &productRpc.SendSmsResponse{}, nil
}
